package munyorderweb;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import munyorderweb_DB.Change_Bean;

public class Category_conf extends HttpServlet {

	String sql;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		order(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		order(req,resp);
	}

	protected void order(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		//カテゴリー変更画面
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html; charset=utf-8");

		ArrayList<Change_Bean> list = new ArrayList<Change_Bean>();
		Change_Bean change = null;

		int i;

		//カテゴリー内容の変更に必要な情報を入力フォームから引き抜き、Bean型へ詰め替え
		list = new ArrayList<Change_Bean>();
		String[] C_no = req.getParameterValues("no");
		String[] C_name = req.getParameterValues("name");
		for(i = 0; i<C_no.length; i++){
			System.out.println(C_no[i]);
			System.out.println(C_name[i]);
			change = new Change_Bean();
			//カテゴリーナンバー、およびカテゴリーネームが記入されている場合はそのままBean型へ
			if(C_no[i] != "" && C_name[i] != ""){
				change.setCategory_no(Integer.parseInt(C_no[i]));
				change.setCategory_name(C_name[i]);
			}else{
				//名前がnullの場合は空白をセットしてBean型へ
				change.setCategory_no(Integer.parseInt(C_no[i]));
				change.setCategory_name("");
			}
			//セットしたBean型をArray＜Bean＞に投入
			list.add(change);
		}
		//新規登録分
		if(req.getParameterValues("newName") != null){
			String[] newName = req.getParameterValues("newName");
			for(int j=0; j<newName.length; j++){
				System.out.println(newName[j]);
				change = new Change_Bean();
				if(newName[j] != ""){
					//新規分
					//新規登録分は全て一度カテゴリーナンバー0でBean型へ詰め込む
					change.setCategory_no(0);
					change.setCategory_name(newName[j]);
					list.add(change);
				}
			}
		}

		HttpSession session_M = req.getSession();
		session_M.setAttribute("Category", list);

		//表示用Jspファイルを呼出して画面上に表示
		req.setAttribute("Category_conf", list);
		RequestDispatcher dispatcher = req.getRequestDispatcher("Category_conf.jsp");
		dispatcher.include(req, resp);
	}
}
